package com.san.common.auth.util;

import com.san.common.auth.enums.ServiceErrorCodeEnum;
import com.san.common.auth.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

import java.util.Random;
import java.util.UUID;

public class RandomUtils {

    final static char[] sources = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9'};
    @NonNull
    public static String randomUUIDWithoutDash() {
        return StringUtils.remove(UUID.randomUUID().toString(), '-');
    }

    /**
     * 生成随机验证码
     * @param size: 验证码长度
     * @return
     */
    public static String authCode(int size) {
        if (size <= 0) throw new ServiceException(ServiceErrorCodeEnum.PARAMETER_ERROR.getDesc());
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(sources[random.nextInt(sources.length)]);
        }
        return sb.toString();
    }
}
